import React, { useReducer } from 'react';
import { Input, Select, Checkbox, Tooltip } from 'antd';
import { useDeepCompareEffect } from 'ahooks';
import isPlainObject from 'lodash/isPlainObject';
import get from 'lodash/get';
import NodePathSelect from '../NodePathSelect';
import styles from './styles.less';

const { Option } = Select;

const initialState = {
  value: {
    lhsPath: [],
    op: 'eq',
  },
};

function reducer(state, action) {
  const { type, payload } = action;

  if (type === 'sync_props') {
    return {
      ...state,
      ...payload,
    };
  }

  if (type === 'change_value') {
    return {
      ...state,
      value: { ...state.value, ...payload },
    };
  }

  throw new Error();
}

function Condition({
  value,
  disabled = false,
  readOnly = false,
  dataSource = { treeData: [], select: [] },
  onChange,
}) {
  // const [state, setState] = useControllableValue(props);

  const [state, dispatch] = useReducer(reducer, initialState);

  useDeepCompareEffect(() => {
    if (isPlainObject(value) && Array.isArray(get(value, 'lhsPath'))) {
      dispatch({ type: 'sync_props', payload: { value } });
    }
  }, [value, dispatch]);

  return (
    <>
      <div style={{ color: 'rgba(0, 0, 0, 0.85)' }}>条件：</div>
      <NodePathSelect
        value={state.value.lhsPath}
        treeData={dataSource.treeData}
        onChange={value => {
          dispatch({ type: 'change_value', payload: { lhsPath: value } });
          onChange({ ...state.value, lhsPath: value });
        }}
        disabled={disabled}
        readOnly={readOnly}
        className={styles.path}
      />
      <Select
        value={state.value.op}
        onChange={value => {
          dispatch({ type: 'change_value', payload: { op: value } });
          onChange({ ...state.value, op: value });
        }}
        disabled={disabled}
        readOnly={readOnly}
        className={styles.op}
      >
        {dataSource.select.map(k => (
          <Option key={k.value} value={k.value}>
            {k.title}
          </Option>
        ))}
      </Select>
      <Input
        value={get(state, 'value.rhs.stringValue')}
        onChange={e => {
          // let format;
          // // 猜测用户要的是`number`还是`string`
          // if (get(value, 'rhs') && ['string', 'number'].includes(format)) {
          //   format = typeof get(value, 'rhs');
          // } else {
          //   format = /^\d+$/.test(e.target.value) ? 'number' : 'string';
          // }

          // const newValue =
          //   format === 'string' ? String(e.target.value) : parseInt(e.target.value, 10);

          const rhs = {
            stringValue: e.target.value,
            isString:
              typeof get(state, 'value.rhs.isString') === 'boolean'
                ? get(state, 'value.rhs.isString')
                : true,
          };

          dispatch({
            type: 'change_value',
            payload: {
              rhs,
            },
          });
          onChange({
            ...state.value,
            rhs,
          });
        }}
        placeholder="值"
        disabled={disabled}
        readOnly={readOnly}
        className={styles.rhs}
        allowClear
        addonAfter={
          <Tooltip title="是否当成字符串处理">
            <Checkbox
              checked={
                typeof get(state, 'value.rhs.isString') === 'boolean'
                  ? get(state, 'value.rhs.isString')
                  : true
              }
              onChange={e => {
                const rhs = {
                  stringValue: get(state, 'value.rhs.stringValue') || '',
                  isString: e.target.checked,
                };

                dispatch({
                  type: 'change_value',
                  payload: {
                    rhs,
                  },
                });

                onChange({
                  ...state.value,
                  rhs,
                });
              }}
            />
          </Tooltip>
        }
      />
    </>
  );
}

export default Condition;
